package com.demo.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractChatServer<T> implements IServer {

	// private static final Log LOG =
	// LogFactory.getLog(AbstractChatServer.class);

	protected static final String NICKNAMEW_VALID = "nickvalid";
	protected static final String NICKNAMEW_NOT_VALID = "NOT_VALID";
	protected static final String DISCONNECT = "bye";
	protected ServerSocket serverSocket;
	protected int port;
	protected int backlog = 128;

	/**
	 * 存放所有连接对应的输出流<br/>
	 * volatile保证并发remove元素的可见性
	 */
	protected volatile ConcurrentHashMap<String, T> chatterMap = new ConcurrentHashMap<>();;

	public AbstractChatServer(int port) {
		this.port = port;
	}

	public AbstractChatServer(int port, int backlog) {
		this.port = port;
		this.backlog = backlog;
	}

	public int getOnlineCount() {
		return chatterMap.size();
	}

	/**
	 * 启动服务器
	 * 
	 * @throws IOException @throws
	 */
	@Override
	public abstract void bootStrap() throws Exception;

	/**
	 * 关闭服务器
	 */
	@Override
	public void shutDown() {

	}

	protected boolean isNickNameExisted(String name) {
		return chatterMap.get(name.trim()) != null;
	}

	/*
	 * 消息显示形式，默认标准输出流
	 */
	protected void showMsg(String msg) {
		System.out.println(msg);
	}

	/**
	 * 发送给所有在线用户
	 * 
	 * @param msg
	 */
	protected abstract void sendToAll(String msg);

	/**
	 * 私信给某个在线用户
	 * 
	 * @param msg
	 * @param nickName
	 */
	protected abstract void sendToPrivate(String msg, String nickName);

}
